package chat.server;

import java.net.Socket;
import java.util.*;

import chat.user.*;

public class GroupProcessor{
	
	private static ArrayList<Group> group_list;
	private static Vector<Group> group_list_new = new Vector<Group>();
	private static Group root = new Group("ROOT");
	//private static ArrayList<User> user_list = new ArrayList<User>();
	
	public GroupProcessor(){
		
		group_list = new ArrayList<Group>();
		
		
		Group g1 = new Group("Test1");
		Group g2 = new Group("Test2");
		
		group_list_new.add(root);
		group_list_new.add(g1);
		group_list_new.add(g2);
		
	}
	
	public static boolean isInList(Group g){
		
		boolean flag=false;
		
		for (Group gr :group_list){
			
			if (gr.getName().equalsIgnoreCase(g.getName())){
				
				flag = true;
			}
			
		}
		
		return flag;
	}
	
	public static boolean addToGroupList(String group_name){
		
		Group new_group = new Group(group_name);
		
		return group_list_new.add(new_group);
		
	}
	
	public static Vector<Group> getGroupList(){
		
		return group_list_new;
	}
	
	public static Group getRoot(){
		return root;
	}
	
	public static Group getGroup(String g){
		
		Group group = null;
		
		for (Group gr: group_list_new){
			
			if (gr.getName().equals(g)) {
				
				return group = gr;
			}
			
		}
		
		return group;
	}
	
	/*public static boolean addUserToGroup(Socket s, Group group){
		
		for (int i=0; i<group_list.size(); i++){
			
			Group g = group_list.get(i);
			
			for (int j=0; j<g.getSocketCount(); j++){
				
				if (g.getSocket(j).equals(s)){
					
					
				}
			}
		}
		
		return getGroup(group).addSocket(s);
		
	}*/
	
	public static void addUserToGroup (User u, Group group){
		
		for (Group g: group_list_new){
			
			if (g.equals(group)){
				
				g.addUser(u);
				
				//u.getRelatedGroup().removeUser(u);
				
				u.updateRelatedGroup(g.getName());
				
			}
		}
	}
	
	public static void registerNewUser (Socket s, User u){
		
		User user = u;
		
		user.addSocket(s);
		
		root.addUser(user);
		
		user.updateRelatedGroup(root.getName());
	}
	
	public static void connectToGroup(String to, String username){
		
		for (Group g: group_list_new){
			
			for (User u: g.getUserList()){
				
				if (u.getUserName().equalsIgnoreCase(username)){
					
					g.getUserList().remove(u.getUserName());
					getGroup(to).addUser(u);
					break;
				}
			}
		}
		
		
		
	}
}
